package mydessertstore.web.servlet;

import mydessertstore.domain.Account;
import mydessertstore.domain.Cart;
import mydessertstore.domain.CartItem;
import mydessertstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;

public class UpdateCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset = UTF-8");

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");

        Iterator<CartItem> cartItems = cart.getAllCartItems();

        while(cartItems.hasNext()){
            CartItem cartItem =(CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();


            try{

                String quantityString = req.getParameter(itemId);

                //拿到用户输入的text里面的quantity数字
                int quantity = Integer.parseInt(quantityString);
                cart.setQuantityByItemId(itemId,quantity);

                //取到值以后如果无数量就不显示了
                if(quantity<1)
                {
                    cartItems.remove();
                }

            }catch(Exception e){

            }


        }

        //日志
        Account account;
        account = (Account) session.getAttribute("account");
        if(account!=null) {

            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + " 更新购物车中数量" ;
            logService.insertLogInfo(account.getUsername(), logInfo);
        }
        else{
            LogService logService = new LogService();
            String logInfo = logService.logInfo(" ") + " 更新购物车中数量" ;
            logService.insertLogInfo("未登录用户", logInfo);
        }
        //日志结束

        req.getRequestDispatcher(CART_FORM).forward(req,resp);

    }
}
